import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;

public class Solution {
    /**
     *
     * @param root TreeNode类
     * @return int整型ArrayList<ArrayList<>>
     */
    public ArrayList<ArrayList<Integer>> zigzagLevelOrder (TreeNode root) {
        // write code here
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offerLast(root);
        int depth = 1;

        while (!deque.isEmpty()) {
            int len = deque.size();
            ArrayList<Integer> list = new ArrayList<>();
            if (depth % 2 == 0) {
                for (int i = 0; i < len; ++i) {
                    TreeNode temp = deque.pollLast();
                    list.add(temp.val);
                    if (temp.right != null) deque.offerFirst(temp.right);
                    if (temp.left != null) deque.offerFirst(temp.left);
                }
            } else {
                for (int i = 0; i < len; ++i) {
                    TreeNode temp = deque.pollFirst();
                    list.add(temp.val);
                    if (temp.left != null) deque.offerLast(temp.left);
                    if (temp.right != null) deque.offerLast(temp.right);

                }
            }
            res.add(list);
            depth++;
        }
        return res;
    }
}

/*思路和代码都更简单*/
class Solution2 {
    /**
     *
     * @param root TreeNode类
     * @return int整型ArrayList<ArrayList<>>
     */
    public ArrayList<ArrayList<Integer>> zigzagLevelOrder (TreeNode root) {
        // write code here
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offerLast(root);
        int depth = 1;

        while (!deque.isEmpty()) {
            int len = deque.size();
            ArrayList<Integer> list = new ArrayList<>();

            for (int i = 0; i < len; ++i) {
                TreeNode temp = deque.poll();
                if (depth % 2 == 0) list.add(0, temp.val);
                else list.add(temp.val);
                if (temp.left != null) deque.offer(temp.left);
                if (temp.right != null) deque.offer(temp.right);
            }

            res.add(list);
            depth++;
        }
        return res;
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
